package crypto

import (
	"crypto/aes"
	"encoding/base64"
	"encoding/hex"
)

// ECB
func (_aes CryptoUtil) EncryptAes(src []byte, key []byte) ([]byte, error) {
	cipher, err := aes.NewCipher(generateKey(key))
	if err != nil {
		return nil, err
	}
	length := (len(src) + aes.BlockSize) / aes.BlockSize
	plain := make([]byte, length*aes.BlockSize)
	copy(plain, src)
	pad := byte(len(plain) - len(src))
	for i := len(src); i < len(plain); i++ {
		plain[i] = pad
	}
	dst := make([]byte, len(plain))
	// 分组分块加密
	for bs, be := 0, cipher.BlockSize(); bs <= len(src); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Encrypt(dst[bs:be], plain[bs:be])
	}
	return dst, nil
}
func (_aes CryptoUtil) EncryptAesStr(src string, key []byte) ([]byte, error) {
	return _aes.EncryptAes([]byte(src), key)
}

func (_aes CryptoUtil) EncryptAesHex(src []byte, key []byte) (string, error) {
	encrypt, err := _aes.EncryptAes(src, key)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(encrypt), nil
}

func (_aes CryptoUtil) EncryptAesHexStr(src string, key []byte) (string, error) {
	return _aes.EncryptAesHex([]byte(src), key)
}

func (_aes CryptoUtil) EncryptAesBase64(src []byte, key []byte) (string, error) {
	encrypt, err := _aes.EncryptAes(src, key)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(encrypt), nil
}

func (_aes CryptoUtil) EncryptAesBase64Str(src string, key []byte) (string, error) {
	return _aes.EncryptAesBase64([]byte(src), key)
}

func (_aes CryptoUtil) DecryptAes(src []byte, key []byte) (string, error) {
	cipher, err := aes.NewCipher(generateKey(key))
	if err != nil {
		return "", err
	}
	decrypted := make([]byte, len(src))
	//
	for bs, be := 0, cipher.BlockSize(); bs < len(src); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Decrypt(decrypted[bs:be], src[bs:be])
	}

	trim := 0
	if len(decrypted) > 0 {
		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
	}
	return string(decrypted[:trim]), nil
}

func (_aes CryptoUtil) DecryptAesHex(src string, key []byte) (string, error) {
	decodeStr, err := hex.DecodeString(src)
	if err != nil {
		return "", err
	}
	decrypt, err := _aes.DecryptAes(decodeStr, key)
	if err != nil {
		return "", err
	}
	return decrypt, nil
}

func (_aes CryptoUtil) DecryptAesBase64(src string, key []byte) (string, error) {
	decodeStr, err := base64.StdEncoding.DecodeString(src)
	if err != nil {
		return "", err
	}
	decrypt, err := _aes.DecryptAes(decodeStr, key)
	if err != nil {
		return "", err
	}
	return decrypt, nil
}

func generateKey(key []byte) (genKey []byte) {
	genKey = make([]byte, 16)
	copy(genKey, key)
	for i := 16; i < len(key); {
		for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
			genKey[j] ^= key[i]
		}
	}
	return genKey
}
